package com.yk.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yk.system.entity.Dept;
import com.yk.common.core.constant.UserConstants;
import com.yk.common.core.exception.ServiceException;
import com.yk.common.core.utils.StringUtils;
import com.yk.common.core.utils.TreeBuildUtils;
import com.yk.common.core.utils.LoginHelper;
import com.yk.system.mapper.DeptMapper;
import com.yk.system.service.DeptService;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author lmx
 * @description
 * @date 2023/10/16 17:34
 */
@Service
public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements DeptService {

    @Override
    public int updateBatch(List<Dept> list) {
        return baseMapper.updateBatch(list);
    }

    @Override
    public int batchInsert(List<Dept> list) {
        return baseMapper.batchInsert(list);
    }

    @Override
    public void checkDeptDataScope(Long deptId) {
        if (!LoginHelper.isAdmin()) {
            Dept dept = new Dept();
            dept.setId(deptId);
            List<Dept> depts = this.selectDeptList(dept);
            if (CollUtil.isEmpty(depts)) {
                throw new ServiceException("没有权限访问部门数据！");
            }
        }
    }

    @Override
    public List<Tree<Long>> selectDeptTreeList(Dept dept) {
        // 只查询未禁用部门
        dept.setStatus(UserConstants.DEPT_NORMAL);
        List<Dept> depts = this.selectDeptList(dept);
        return buildDeptTreeSelect(depts);
    }


    @Override
    public List<Tree<Long>> buildDeptTreeSelect(List<Dept> depts) {
        if (CollUtil.isEmpty(depts)) {
            return CollUtil.newArrayList();
        }
        return TreeBuildUtils.build(depts, (dept, tree) ->
                tree.setId(dept.getId())
                        .setParentId(dept.getParentId())
                        .setName(dept.getDeptName())
                        .setWeight(dept.getOrderNum()));
    }


    @Override
    public List<Dept> selectDeptList(Dept dept) {
        LambdaQueryWrapper<Dept> lamdba = new LambdaQueryWrapper<>();
        lamdba.eq(ObjectUtil.isNotNull(dept.getId()), Dept::getId, dept.getId());
        lamdba.eq(ObjectUtil.isNotNull(dept.getParentId()), Dept::getParentId, dept.getParentId());
        lamdba.like(StringUtils.isNotBlank(dept.getDeptName()), Dept::getDeptName, dept.getDeptName());
        lamdba.eq(StringUtils.isNotBlank(dept.getStatus()), Dept::getStatus, dept.getStatus());
        lamdba.orderByAsc(Dept::getParentId);
        return baseMapper.selectList(lamdba);
    }
}
